<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/2
 * Time: 15:41
 */

namespace app\models;

use yii;
use yii\db\Query;

class InRepo extends BaseModel
{

    public function __construct()
    {
        $this->table = yii::$app->db->tablePrefix . 'in_repo';
    }

    public function all($where = [], $offset = false, $limit = false, $order = false)
    {
        $db = new Query();
        $db->select('*')->from($this->table);
        if (!empty($where['id'])) {
            if (is_array($where['id'])) {
                $db->andWhere(['in', 'id', $where['id']]);
            }
        }
        if (!empty($where['staff'])) $db->andWhere(['staff' => $where['staff']]);
        if (!empty($where['status'])) $db->andWhere(['status' => $where['status']]);
        if (!empty($where['number_no'])) $db->andWhere(['number_no' => $where['number_no']]);
        if (!empty($where['begin_time'])) $db->andWhere(['>=', 'date', $where['begin_time']]);
        if (!empty($where['begin_time'])) $db->andWhere(['<=', 'date', $where['begin_time']]);

        if ($order) $db->orderBy($order);
        if ($offset) $db->offset($offset);
        if ($limit) $db->limit($limit);
        return $db->all();
    }

    public function size($where = [])
    {
        $db = new Query();
        $db->select('count(id) as num ')->from($this->table);
        if (!empty($where['staff'])) $db->andWhere(['staff' => $where['staff']]);
        if (!empty($where['status'])) $db->andWhere(['status' => $where['status']]);
        if (!empty($where['number_no'])) $db->andWhere(['number_no' => $where['number_no']]);
        if (!empty($where['begin_time'])) $db->andWhere(['>=', 'date', $where['begin_time']]);
        if (!empty($where['begin_time'])) $db->andWhere(['<=', 'date', $where['begin_time']]);
        $re = $db->one();
        return $re ? $re['num'] : 0;
    }

    public function one($where = [])
    {
        $db = new Query();
        $db->select('*')->from($this->table);
        if (!empty($where['id'])) $db->andWhere(['id' => $where['id']]);

        return $db->limit(1)->one();
    }

    public function getNumber()
    {
        $db = new Query();
        $db->select('*')->from($this->table);
        $db->andWhere(['date' => date('Y-m-d')]);
        $db->orderBy(['time' => SORT_DESC])
            ->limit(1)->one();
        return $db->one();
    }
}